<template>
    <div class="search-form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :label-width="config.labelWidth || 'auto'"
        :label-position="config.labelPosition || 'right'"
        :inline="config.inline"
        @submit.prevent="handleSubmit"
      >
        <el-row :gutter="config.gutter || 20">
          <template v-for="(item, index) in displayedItems" :key="item.field">
            <el-col
              :span="item.colSpan || config.span || 6"
              :xs="24"
              :sm="12"
              :md="item.colSpan || config.span || 8"
              :lg="item.colSpan || config.span || 6"
              v-if="!item.hidden"
            >
              <el-form-item
                :label="item.label"
                :prop="item.field"
              >
                <component
                  :is="getFormItemComponent(item)"
                  v-bind="getComponentProps(item)"
                  v-model="formData[item.field]"
                  v-on="item.events || {}"
                ></component>
              </el-form-item>
            </el-col>
          </template>
  
          <!-- 按钮组 -->
          <el-col
            :span="config.span || 6"
            :xs="24"
            :sm="12"
            :md="config.span || 8"
            :lg="config.span || 6"
            class="button-group"
          >
            <el-form-item>
              <el-button type="primary" @click="handleSubmit">
                {{ config.submitButtonText || '搜索' }}
              </el-button>
              <el-button v-if="config.showResetButton !== false" @click="handleReset">
                {{ config.resetButtonText || '重置' }}
              </el-button>
              <el-button
                v-if="config.collapsible && hasCollapsibleItems"
                type="text"
                @click="toggleCollapse"
              >
                {{ collapsed ? config.expandButtonText || '展开' : config.collapseButtonText || '收起' }}
                <el-icon>
                  <component :is="collapsed ? 'ArrowDown' : 'ArrowUp'"></component>
                </el-icon>
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, computed, reactive, watch, onMounted } from 'vue';
  // import { ElMessage } from 'element-plus';
  import { ArrowDown, ArrowUp } from '@element-plus/icons-vue';
  import { 
    SearchFormConfig,
    FormItemConfig,
    FormItemType,
    BaseFormItemConfig
  } from './types';
  import { getFormItemComponent } from './components';
  
  // 定义组件的 props
  const props = defineProps<{
    config: SearchFormConfig;
    modelValue: Record<string, any>;
  }>();
  
  // 定义组件的 emit
  const emit = defineEmits<{
    (e: 'update:modelValue', value: Record<string, any>): void;
    (e: 'search', value: Record<string, any>): void;
    (e: 'reset'): void;
  }>();
  
  // 表单引用
  const formRef = ref();
  
  // 表单数据
  const formData = reactive<Record<string, any>>({});
  
  // 初始化默认值
  const initDefaultValues = () => {
    const defaultValues: Record<string, any> = {};
    props.config.formItems.forEach(item => {
      console.log(item)
      if (item.defaultValue !== undefined) {
        defaultValues[item.field] = item.defaultValue;
      } else {
        // 根据类型设置默认值
        switch (item.type) {
          case FormItemType.CHECKBOX_GROUP:
            defaultValues[item.field] = [];
            break;
          case FormItemType.SWITCH:
            defaultValues[item.field] = false;
            break;
          case FormItemType.NUMBER:
            defaultValues[item.field] = undefined;
            break;
          default:
            defaultValues[item.field] = '';
        }
      }
    });
    console.log(formData, defaultValues, props.modelValue)
    // 合并来自 modelValue 的值
    Object.assign(formData, defaultValues, props.modelValue);
  };
  
  // 折叠状态
  const collapsed = ref(props.config.defaultCollapse !== false);
  
  // 是否有可折叠的项
  const hasCollapsibleItems = computed(() => {
    return props.config.formItems.some(item => item.collapsible);
  });
  
  // 根据折叠状态显示的表单项
  const displayedItems = computed(() => {
    // 根据 order 排序
    const sortedItems = [...props.config.formItems].sort((a, b) => {
      const orderA = a.order !== undefined ? a.order : 999;
      const orderB = b.order !== undefined ? b.order : 999;
      return orderA - orderB;
    });
  
    if (collapsed.value && hasCollapsibleItems.value) {
      return sortedItems.filter(item => !item.collapsible);
    }
    return sortedItems;
  });
  
  // 切换折叠状态
  const toggleCollapse = () => {
    collapsed.value = !collapsed.value;
  };
  
  // 获取表单项的规则
  const getFormItemRules = (item: FormItemConfig) => {
    if (item.rules) {
      return item.rules;
    }
  
    if (item.required) {
      return { required: true, message: `请输入${item.label}`, trigger: 'change' };
    }
  
    return undefined;
  };
  
  // 获取表单项对应的组件
  const getComponentProps = (item: FormItemConfig) => {
    // 基础属性
    const baseProps: Record<string, any> = {
      placeholder: item.placeholder || `请输入${item.label}`,
      disabled: item.disabled,
      clearable: item.clearable !== false,
      ...((item as BaseFormItemConfig).props || {}),
    };
  
    // 根据不同类型添加特定属性
    switch (item.type) {
      case FormItemType.INPUT:
        return {
          ...baseProps,
          maxlength: item.maxLength,
          minlength: item.minLength,
          'show-word-limit': item.showWordLimit,
          'prefix-icon': item.prefixIcon,
          'suffix-icon': item.suffixIcon,
        };
      case FormItemType.SELECT:
        return {
          ...baseProps,
          options: item.options,
          multiple: item.multiple,
          filterable: item.filterable,
          remote: item.remote,
          'remote-method': item.remoteMethod,
          loading: item.loading,
        };
      case FormItemType.DATE_PICKER:
        return {
          ...baseProps,
          type: item.dateType,
          format: item.format,
          'value-format': item.valueFormat,
          'start-placeholder': item.startPlaceholder,
          'end-placeholder': item.endPlaceholder,
          'range-separator': item.rangeSeparator || '-',
        };
      case FormItemType.RADIO_GROUP:
        return {
          ...baseProps,
          options: item.options,
          button: item.button,
        };
      case FormItemType.CHECKBOX_GROUP:
        return {
          ...baseProps,
          options: item.options,
          min: item.min,
          max: item.max,
          button: item.button,
        };
      case FormItemType.TREE_SELECT:
        return {
          ...baseProps,
          data: item.data,
          'check-strictly': item.checkStrictly,
          multiple: item.multiple,
          'check-on-click-node': item.checkOnClickNode,
          'default-expand-all': item.defaultExpandAll,
          filterable: item.filterable,
          'filter-method': item.filterMethod,
        };
      case FormItemType.NUMBER:
        return {
          ...baseProps,
          min: item.min,
          max: item.max,
          step: item.step,
          precision: item.precision,
          'controls-position': item.controlsPosition,
          controls: item.controls,
        };
      case FormItemType.SWITCH:
        return {
          ...baseProps,
          'active-text': item.activeText,
          'inactive-text': item.inactiveText,
          'active-value': item.activeValue,
          'inactive-value': item.inactiveValue,
        };
      case FormItemType.CASCADER:
        return {
          ...baseProps,
          options: item.options,
          filterable: item.filterable,
          'show-all-levels': item.showAllLevels,
          multiple: item.multiple,
        };
      case FormItemType.CUSTOM:
        return {
          ...baseProps,
        };
      default:
        return baseProps;
    }
  };
  
  // 处理表单提交
  const handleSubmit = async () => {
    emit('search', { ...formData });
    emit('update:modelValue', { ...formData });
    // try {
    //   await formRef.value.validate();

    // } catch (error) {
    //   ElMessage.error('表单验证失败，请检查输入');
    //   console.error('Form validation error:', error);
    // }
  };
  
  // 处理表单重置
  const handleReset = () => {
    if (!formRef.value) return;
    formRef.value.resetFields();
    // initDefaultValues();
    emit('reset');
    emit('update:modelValue', { ...formData });
  };
  
  // 监听 modelValue 变化
  watch(
    () => props.modelValue,
    (newVal) => {
      // 只更新存在于 formData 中的字段
      Object.keys(formData).forEach(key => {
        if (newVal && newVal[key] !== undefined) {
          formData[key] = newVal[key];
        }
      });
    },
    { deep: true }
  );
  
  // 监听 formData 变化
  watch(
    formData,
    (newVal) => {
      emit('update:modelValue', { ...newVal });
    },
    { deep: true }
  );
  
  // 初始化
  onMounted(() => {
    initDefaultValues();
  });
  </script>
  
  <style scoped>
  .search-form-container {
    width: 100%;
    margin-bottom: 16px;
  }
  
  .button-group {
    display: flex;
    align-items: center;
  }
  
  @media (max-width: 768px) {
    :deep(.el-form-item) {
      margin-bottom: 12px;
    }
  }
  </style>